"""
商品管理相关的API
包括商品列表、详情、创建、更新等功能
"""
from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, current_user
from sqlalchemy.exc import SQLAlchemyError
from marshmallow import ValidationError

from app.extensions import db
from app.models.product import Product, ProductSpecification, ProductVariant, ProductStatus
from app.schemas.product import ProductSchema, ProductCreateSchema, ProductUpdateSchema, ProductSpecificationSchema, ProductVariantSchema
from app.utils.errors import NotFoundError, BadRequestError, ForbiddenError
from app.utils.upload import save_file, delete_file
from app.api.v1 import api_v1

@api_v1.route('/products', methods=['GET'])
def get_products():
    """获取商品列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    status = request.args.get('status')
    keyword = request.args.get('keyword')
    
    # 构建查询
    query = Product.query
    
    if status:
        query = query.filter_by(status=status)
    
    if keyword:
        query = query.filter(Product.name.ilike(f'%{keyword}%') | 
                            Product.sku.ilike(f'%{keyword}%'))
    
    # 分页
    pagination = query.order_by(Product.created_at.desc()).paginate(page=page, per_page=per_page)
    
    # 序列化响应
    schema = ProductSchema(many=True)
    products = schema.dump(pagination.items)
    
    return jsonify({
        "total": pagination.total,
        "pages": pagination.pages,
        "page": page,
        "per_page": per_page,
        "products": products
    }), 200

@api_v1.route('/products/<int:product_id>', methods=['GET'])
def get_product(product_id):
    """获取商品详情"""
    product = Product.query.get_or_404(product_id)
    
    # 序列化响应，包含规格和变体信息
    schema = ProductSchema()
    result = product.to_dict(include_specs=True, include_variants=True)
    
    return jsonify(result), 200

@api_v1.route('/products', methods=['POST'])
@jwt_required()
def create_product():
    """创建商品"""
    data = request.get_json()
    
    if not data:
        raise BadRequestError("请求参数为空")
    
    # 验证数据
    schema = ProductCreateSchema()
    try:
        # 使用schema验证数据
        validated_data = schema.load(data)
    except ValidationError as e:
        return jsonify({"msg": "数据验证错误", "errors": e.messages}), 400
    
    # 创建商品
    product = Product(
        name=data['name'],
        description=data.get('description'),
        price=data['price'],
        stock=data['stock'],
        sku=data['sku'],
        status=data.get('status', ProductStatus.DRAFT.value)
    )
    
    db.session.add(product)
    db.session.flush()  # 获取商品ID，用于创建规格和变体
    
    # 添加规格
    if 'specifications' in data and data['specifications']:
        for spec_data in data['specifications']:
            spec = ProductSpecification(
                product_id=product.id,
                name=spec_data['name']
            )
            spec.option_list = spec_data['options']
            db.session.add(spec)
    
    # 添加变体
    if 'variants' in data and data['variants']:
        for variant_data in data['variants']:
            variant = ProductVariant(
                product_id=product.id,
                sku=variant_data['sku'],
                price=variant_data['price'],
                stock=variant_data['stock']
            )
            variant.specifications = variant_data['specifications']
            db.session.add(variant)
    
    try:
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"创建商品失败: {str(e)}")
        return jsonify({"msg": "创建商品失败", "error": str(e)}), 500
    
    return jsonify({
        "msg": "商品创建成功",
        "product": product.to_dict(include_specs=True, include_variants=True)
    }), 201

@api_v1.route('/products/<int:product_id>', methods=['PUT'])
@jwt_required()
def update_product(product_id):
    """更新商品"""
    product = Product.query.get_or_404(product_id)
    data = request.get_json()
    
    if not data:
        raise BadRequestError("请求参数为空")
    
    # 验证数据
    schema = ProductUpdateSchema()
    try:
        # 使用schema验证数据
        validated_data = schema.load(data)
    except ValidationError as e:
        return jsonify({"msg": "数据验证错误", "errors": e.messages}), 400
    
    # 更新商品基本信息
    if 'name' in data:
        product.name = data['name']
    if 'description' in data:
        product.description = data['description']
    if 'price' in data:
        product.price = data['price']
    if 'stock' in data:
        product.stock = data['stock']
    if 'status' in data:
        product.status = data['status']
    
    try:
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"更新商品失败: {str(e)}")
        return jsonify({"msg": "更新商品失败", "error": str(e)}), 500
    
    return jsonify({
        "msg": "商品更新成功",
        "product": product.to_dict()
    }), 200

@api_v1.route('/products/<int:product_id>', methods=['DELETE'])
@jwt_required()
def delete_product(product_id):
    """删除商品"""
    product = Product.query.get_or_404(product_id)
    
    try:
        # 删除关联的规格和变体
        ProductSpecification.query.filter_by(product_id=product.id).delete()
        ProductVariant.query.filter_by(product_id=product.id).delete()
        
        # 删除商品
        db.session.delete(product)
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"删除商品失败: {str(e)}")
        return jsonify({"msg": "删除商品失败", "error": str(e)}), 500
    
    return jsonify({
        "msg": "商品删除成功"
    }), 200

@api_v1.route('/products/<int:product_id>/specifications', methods=['POST'])
@jwt_required()
def add_product_specification(product_id):
    """添加商品规格"""
    product = Product.query.get_or_404(product_id)
    data = request.get_json()
    
    # 验证数据
    schema = ProductSpecificationSchema()
    try:
        # 使用schema验证数据
        validated_data = schema.load(data)
    except ValidationError as e:
        return jsonify({"msg": "数据验证错误", "errors": e.messages}), 400
    
    # 创建规格
    spec = ProductSpecification(
        product_id=product.id,
        name=data['name']
    )
    spec.option_list = data['options']
    
    try:
        db.session.add(spec)
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"添加商品规格失败: {str(e)}")
        return jsonify({"msg": "添加商品规格失败", "error": str(e)}), 500
    
    return jsonify({
        "msg": "商品规格添加成功",
        "specification": spec.to_dict()
    }), 201

@api_v1.route('/products/<int:product_id>/variants', methods=['POST'])
@jwt_required()
def add_product_variant(product_id):
    """添加商品变体"""
    product = Product.query.get_or_404(product_id)
    data = request.get_json()
    
    # 验证数据
    schema = ProductVariantSchema(context={'product_id': product_id})
    try:
        # 使用schema验证数据
        validated_data = schema.load(data)
    except ValidationError as e:
        return jsonify({"msg": "数据验证错误", "errors": e.messages}), 400
    
    # 创建变体
    variant = ProductVariant(
        product_id=product.id,
        sku=data['sku'],
        price=data['price'],
        stock=data['stock']
    )
    variant.specifications = data['specifications']
    
    try:
        db.session.add(variant)
        db.session.commit()
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"添加商品变体失败: {str(e)}")
        return jsonify({"msg": "添加商品变体失败", "error": str(e)}), 500
    
    return jsonify({
        "msg": "商品变体添加成功",
        "variant": variant.to_dict()
    }), 201

@api_v1.route('/products/sku/<sku>', methods=['GET'])
def get_product_by_sku(sku):
    """通过SKU获取商品"""
    product = Product.query.filter_by(sku=sku).first()
    
    if not product:
        return jsonify({"msg": "商品不存在"}), 404
    
    return jsonify(product.to_dict(include_specs=True, include_variants=True)), 200
